package com.fc.mall.decoration.link.service;

import com.fc.mall.decoration.link.dao.LinkRepository;
import com.fc.mall.decoration.link.exception.LinkNotFoundException;
import com.fc.mall.decoration.link.model.Link;
import com.fc.mall.decoration.link.object.LinkCreate;
import com.fc.mall.decoration.link.object.LinkUpdate;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Slf4j
@Service
public class LinkService {
    @Autowired
    private LinkRepository linkRepository;

    @Autowired
    private MapperFacade mapperFacade;

    public Link createLink(LinkCreate linkCreate) {
        Link link = Link.createNew();
        mapperFacade.map(linkCreate, link);
        Link createdLink = linkRepository.save(link);
        return createdLink;
    }

    public Link updateLink(String linkId, LinkUpdate linkUpdate) {
        Link link = getLink(linkId);
        mapperFacade.map(linkUpdate, link);
        link.setUpdatedAt(new DateTime());
        Link updatedLink = linkRepository.save(link);
        return updatedLink;
    }

    public Link getLink(String linkId) {
        Optional<Link> linkOptional = linkRepository.findById(linkId);
        if (!linkOptional.isPresent()) {
            throw new LinkNotFoundException(linkId);
        }
        return linkOptional.get();
    }

    public void deleteLink(String linkId) {
        Link link = getLink(linkId);
        linkRepository.delete(link);
    }
}
